/*
 * 代号：凤凰
 * http://www.jphenix.org
 * 2017年1月26日
 * V4.0
 */
package com.jphenix.sdk.ftp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import com.jphenix.standard.docs.ClassInfo;

/**
 * FTP客户端（父类）
 * 该类从JDK1.7中获取到的，因为不同版本的JDK的FTP支持方法有变化
 * 所以将该部分代码提取出来
 * @author mbg
 */
@ClassInfo({"2024-03-29 10:22","FTP客户端（父类）"})
public abstract class FtpClient implements java.io.Closeable {

    private static final int FTP_PORT = 21;

    public enum TransferType {

        ASCII, BINARY, EBCDIC
    }

    /**
     * 默认端口
     */
    public static final int defaultPort() {
        return FTP_PORT;
    }

    /**
     * 创建FTP客户端实例
     * @return FTP客户端实例
     * 2024年3月29日
     * @author MBG
     */
    public static FtpClient create() {
        FtpClientProvider provider = FtpClientProvider.provider();
        return provider.createFtpClient();
    }

    /**
     * 创建FTP客户端实例
     * @param dest 目标连接地址信息对象
     * @return FTP客户端实例
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public static FtpClient create(InetSocketAddress dest) throws Exception {
        FtpClient client = create();
        if (dest != null) {
            client.connect(dest);
        }
        return client;
    }

    /**
     * 创建FTP客户端实例
     * @param dest 目标地址
     * @return FTP客户端实例
     * @throws Exception 异常
     */
    public static FtpClient create(String dest) throws Exception {
        return create(new InetSocketAddress(dest, FTP_PORT));
    }

    /**
     * 设置是否启用PASV被动模式
     * @param passive 是否启用PASV被动模式
     * @return 当前类实例
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient enablePassiveMode(boolean passive);

    /**
     * 当前是否为PASV被动模式
     * @return 是否为PASV被动模式
     * 2024年3月29日
     * @author MBG
     */
    public abstract boolean isPassiveModeEnabled();

    /**
     * 设置连接超时时间（单位：毫秒）
     * @param timeout 连接超时时间
     * @return 当前类实例
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient setConnectTimeout(int timeout);

    /**
     * 返回连接超时时间（单位：毫秒）
     * @return 连接超时时间
     * 2024年3月29日
     * @author MBG
     */
    public abstract int getConnectTimeout();

    /**
     * 设置读取超时时间（单位：毫秒）
     * @param timeout 读取超时时间
     * @return 当前类实例
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient setReadTimeout(int timeout);

    /**
     * 返回读取超时时间（单位：毫秒）
     * @return 读取超时时间
     * 2024年3月29日
     * @author MBG
     */
    public abstract int getReadTimeout();

    /**
     * 设置代理
     * @param p 代理信息对象
     * @return 当前类实例
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient setProxy(Proxy p);

    /**
     * 返回代理配置信息
     * @return 代理配置信息
     * 2024年3月29日
     * @author MBG
     */
    public abstract Proxy getProxy();

    /**
     * 返回当前是否已连接
     * @return 当前是否已连接
     * 2024年3月29日
     * @author MBG
     */
    public abstract boolean isConnected();

    /**
     * 建立连接
     * @param dest 连接目标地址信息
     * @return 当前类实例
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient connect(SocketAddress dest) throws Exception;

    /**
     * 建立连接
     * @param dest 目标地址信息
     * @param timeout 连接超时时间（单位：毫秒）
     * @return 当前类实例
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient connect(SocketAddress dest, int timeout) throws Exception;

    /**
     * 返回当前连接的服务器地址信息对象
     * @return 当前连接的服务器地址信息对象
     * 2024年3月29日
     * @author MBG
     */
    public abstract SocketAddress getServerAddress();

    /**
     * 执行登录
     * @param user       服务器账号
     * @param password   密码
     * @return           当前类实例
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient login(String user, char[] password) throws Exception;

    /**
     * 执行登录
     * @param user       服务器用户名
     * @param password   登录密码
     * @param account    登录账号
     * @return           当前类实例
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient login(String user, char[] password, String account) throws Exception;

    /**
     * 关闭当前连接
     */
    @Override
    public abstract void close() throws IOException;

    /**
     * 返回当前是否已经登录
     * @return 当前是否已经登录
     * 2024年3月29日
     * @author MBG
     */
    public abstract boolean isLoggedIn();

    /**
     * 切换服务器路径
     * @param remoteDirectory 目标路径
     * @return 当前类实例
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient changeDirectory(String remoteDirectory) throws Exception;

    /**
     * 回到上一级文件夹
     * @return 当前类实例
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient changeToParentDirectory() throws Exception;

    /**
     * 返回服务器端当前路径
     * @return 服务器端当前路径
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract String getWorkingDirectory() throws Exception;

    /**
     * 执行 REST 命令
     * @param offset 接收文件位置，起始位置传0
     * @return 当前类实例
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient setRestartOffset(long offset);

    /**
     * 获取远程文件
     * @param name   文件名
     * @param local  本地文件输出流
     * @return       当前类实例
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient getFile(String name, OutputStream local) throws Exception;

    /**
     * 获取远程文件读入流
     * @param name 文件名
     * @return     远程文件读入流
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract InputStream getFileStream(String name) throws Exception;

    /**
     * 返回需要发送文件的输出流
     * @param name 发送文件名
     * @return     发送文件的输出流
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public OutputStream putFileStream(String name) throws Exception {
        return putFileStream(name, false);
    }

    /**
     * 获取发送文件输出流
     * @param name    文件名
     * @param unique  如果要求远程文件是唯一的，则发送 STOU 命令。此命令要求在此目录下的文件名是唯一的，对此命令的响应必须包括产生的用户名
     * @return        文件输出流
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract OutputStream putFileStream(String name, boolean unique) throws Exception;

    /**
     * 执行发送文件
     * @param name  文件名
     * @param local 本地文件读入流
     * @return      当前类实例
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public FtpClient putFile(String name, InputStream local) throws Exception {
        return putFile(name, local, false);
    }

    /**
     * 执行发送文件
     * @param name    文件名
     * @param local   本地文件读入流
     * @param unique  如果要求远程文件是唯一的，则发送 STOU 命令。此命令要求在此目录下的文件名是唯一的，对此命令的响应必须包括产生的用户名
     * @return        当前类实例
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient putFile(String name, InputStream local, boolean unique) throws Exception;

    /**
     * 上传文件
     * @param name   文件名
     * @param local  本地文件读入流
     * @return       当前类实例
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient appendFile(String name, InputStream local) throws Exception;

    /**
     * 重命名远程文件
     * @param from 原名
     * @param to   目标名
     * @return     当前类实例
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient rename(String from, String to) throws Exception;

    /**
     * 删除远程服务器文件
     * @param name 文件名
     * @return     当前类实例
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient deleteFile(String name) throws Exception;

    /**
     * 创建远程路径
     * @param name 路径名
     * @return     当前类实例
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient makeDirectory(String name) throws Exception;

    /**
     * 删除远程路径
     * @param name 路径名
     * @return     当前类实例
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient removeDirectory(String name) throws Exception;

    /**
     * 发送保持连接命令
     * @return 当前类实例
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient noop() throws Exception;

    /**
     * Sends the {@code STAT} command to the server.
     * This can be used while a data connection is open to get a status
     * on the current transfer, in that case the parameter should be
     * {@code null}.
     * If used between file transfers, it may have a pathname as argument
     * in which case it will work as the LIST command except no data
     * connection will be created.
     *
     * @param name an optional {@code String} containing the pathname
     *        the STAT command should apply to.
     * @return the response from the server
     * @throws IOException if an error occured during the transmission.
     * @throws FtpProtocolException if the command was rejected by the server
     */
    public abstract String getStatus(String name) throws Exception;

    /**
     * Sends the {@code FEAT} command to the server and returns the list of supported
     * features in the form of strings.
     *
     * The features are the supported commands, like AUTH TLS, PROT or PASV.
     * See the RFCs for a complete list.
     *
     * Note that not all FTP servers support that command, in which case
     * a {@link FtpProtocolException} will be thrown.
     *
     * @return a {@code List} of {@code Strings} describing the
     *         supported additional features
     * @throws IOException if an error occurs during the transmission.
     * @throws FtpProtocolException if the command is rejected by the server
     */
    public abstract List<String> getFeatures() throws Exception;

    /**
     * Sends the {@code ABOR} command to the server.
     * <p>It tells the server to stop the previous command or transfer. No action
     * will be taken if the previous command has already been completed.</p>
     * <p>This doesn't abort the current session, more commands can be issued
     * after an abort.</p>
     *
     * @return this FtpClient
     * @throws IOException if an error occured during the transmission.
     * @throws FtpProtocolException if the command was rejected by the server
     */
    public abstract FtpClient abort() throws Exception;

    /**
     * Some methods do not wait until completion before returning, so this
     * method can be called to wait until completion. This is typically the case
     * with commands that trigger a transfer like {@link #getFileStream(String)}.
     * So this method should be called before accessing information related to
     * such a command.
     * <p>This method will actually block reading on the command channel for a
     * notification from the server that the command is finished. Such a
     * notification often carries extra information concerning the completion
     * of the pending action (e.g. number of bytes transfered).</p>
     * <p>Note that this will return immediately if no command or action
     * is pending</p>
     * <p>It should be also noted that most methods issuing commands to the ftp
     * server will call this method if a previous command is pending.
     * <p>Example of use:
     * <pre>
     * InputStream in = cl.getFileStream("file");
     * ...
     * cl.completePending();
     * long size = cl.getLastTransferSize();
     * </pre>
     * On the other hand, it's not necessary in a case like:
     * <pre>
     * InputStream in = cl.getFileStream("file");
     * // read content
     * ...
     * cl.close();
     * </pre>
     * <p>Since {@link #close()} will call completePending() if necessary.</p>
     * @return this FtpClient
     * @throws IOException if an error occured during the transfer
     * @throws FtpProtocolException if the command didn't complete successfully
     */
    public abstract FtpClient completePending() throws Exception;

    /**
     * Reinitializes the USER parameters on the FTP server
     *
     * @return this FtpClient
     * @throws IOException if an error occurs during transmission
     * @throws FtpProtocolException if the command fails
     */
    public abstract FtpClient reInit() throws Exception;

    /**
     * Changes the transfer type (binary, ascii, ebcdic) and issue the
     * proper command (e.g. TYPE A) to the server.
     *
     * @param type the {@code TransferType} to use.
     * @return This FtpClient
     * @throws IOException if an error occurs during transmission.
     * @throws FtpProtocolException if the command was rejected by the server
     */
    public abstract FtpClient setType(TransferType type) throws Exception;

    /**
     * Changes the current transfer type to binary.
     * This is a convenience method that is equivalent to
     * {@code setType(TransferType.BINARY)}
     *
     * @return This FtpClient
     * @throws IOException if an error occurs during the transmission.
     * @throws FtpProtocolException if the command was rejected by the server
     * @see #setType(TransferType)
     */
    public FtpClient setBinaryType() throws Exception {
        setType(TransferType.BINARY);
        return this;
    }

    /**
     * Changes the current transfer type to ascii.
     * This is a convenience method that is equivalent to
     * {@code setType(TransferType.ASCII)}
     *
     * @return This FtpClient
     * @throws IOException if an error occurs during the transmission.
     * @throws FtpProtocolException if the command was rejected by the server
     * @see #setType(TransferType)
     */
    public FtpClient setAsciiType() throws Exception {
        setType(TransferType.ASCII);
        return this;
    }

    /**
     * Issues a {@code LIST} command to the server to get the current directory
     * listing, and returns the InputStream from the data connection.
     *
     * <p>{@link #completePending()} <b>has</b> to be called once the application
     * is finished reading from the stream.</p>
     *
     * @param path the pathname of the directory to list, or {@code null}
     *        for the current working directory.
     * @return the {@code InputStream} from the resulting data connection
     * @throws IOException if an error occurs during the transmission.
     * @throws FtpProtocolException if the command was rejected by the server
     * @see #changeDirectory(String)
     * @see #listFiles(String)
     */
    public abstract InputStream list(String path) throws Exception;

    /**
     * Issues a {@code NLST path} command to server to get the specified directory
     * content. It differs from {@link #list(String)} method by the fact that
     * it will only list the file names which would make the parsing of the
     * somewhat easier.
     *
     * <p>{@link #completePending()} <b>has</b> to be called once the application
     * is finished reading from the stream.</p>
     *
     * @param path a {@code String} containing the pathname of the
     *        directory to list or {@code null} for the current working directory.
     * @return the {@code InputStream} from the resulting data connection
     * @throws IOException if an error occurs during the transmission.
     * @throws FtpProtocolException if the command was rejected by the server
     */
    public abstract InputStream nameList(String path) throws Exception;

    /**
     * Issues the {@code SIZE [path]} command to the server to get the size of a
     * specific file on the server.
     * Note that this command may not be supported by the server. In which
     * case -1 will be returned.
     *
     * @param path a {@code String} containing the pathname of the
     *        file.
     * @return a {@code long} containing the size of the file or -1 if
     *         the server returned an error, which can be checked with
     *         {@link #getLastReplyCode()}.
     * @throws IOException if an error occurs during the transmission.
     * @throws FtpProtocolException if the command was rejected by the server
     */
    public abstract long getSize(String path) throws Exception;

    /**
     * Issues the {@code MDTM [path]} command to the server to get the modification
     * time of a specific file on the server.
     * Note that this command may not be supported by the server, in which
     * case {@code null} will be returned.
     *
     * @param path a {@code String} containing the pathname of the file.
     * @return a {@code Date} representing the last modification time
     *         or {@code null} if the server returned an error, which
     *         can be checked with {@link #getLastReplyCode()}.
     * @throws IOException if an error occurs during the transmission.
     * @throws FtpProtocolException if the command was rejected by the server
     */
    public abstract Date getLastModified(String path) throws Exception;

    /**
     * Sets the parser used to handle the directory output to the specified
     * one. By default the parser is set to one that can handle most FTP
     * servers output (Unix base mostly). However it may be necessary for
     * and application to provide its own parser due to some uncommon
     * output format.
     *
     * @param p The {@code FtpDirParser} to use.
     * @return this FtpClient
     * @see #listFiles(String)
     */
    public abstract FtpClient setDirParser(FtpDirParser p);

    /**
     * Issues a {@code MLSD} command to the server to get the specified directory
     * listing and applies the internal parser to create an Iterator of
     * {@link java.net.FtpDirEntry}. Note that the Iterator returned is also a
     * {@link java.io.Closeable}.
     * <p>If the server doesn't support the MLSD command, the LIST command is used
     * instead and the parser set by {@link #setDirParser(java.net.FtpDirParser) }
     * is used instead.</p>
     *
     * {@link #completePending()} <b>has</b> to be called once the application
     * is finished iterating through the files.
     *
     * @param path the pathname of the directory to list or {@code null}
     *        for the current working directoty.
     * @return a {@code Iterator} of files or {@code null} if the
     *         command failed.
     * @throws IOException if an error occured during the transmission
     * @see #setDirParser(FtpDirParser)
     * @see #changeDirectory(String)
     * @throws FtpProtocolException if the command was rejected by the server
     */
    public abstract Iterator<FtpDirEntry> listFiles(String path) throws Exception;

    /**
     * Attempts to use Kerberos GSSAPI as an authentication mechanism with the
     * ftp server. This will issue an {@code AUTH GSSAPI} command, and if
     * it is accepted by the server, will followup with {@code ADAT}
     * command to exchange the various tokens until authentication is
     * successful. This conforms to Appendix I of RFC 2228.
     *
     * @return this FtpClient
     * @throws IOException if an error occurs during the transmission.
     * @throws FtpProtocolException if the command was rejected by the server
     */
    public abstract FtpClient useKerberos() throws Exception;

    /**
     * Returns the Welcome string the server sent during initial connection.
     *
     * @return a {@code String} containing the message the server
     *         returned during connection or {@code null}.
     */
    public abstract String getWelcomeMsg();

    /**
     * Returns the last reply code sent by the server.
     *
     * @return the lastReplyCode or {@code null} if none were received yet.
     */
    public abstract FtpReplyCode getLastReplyCode();

    /**
     * Returns the last response string sent by the server.
     *
     * @return the message string, which can be quite long, last returned
     *         by the server, or {@code null} if no response were received yet.
     */
    public abstract String getLastResponseString();

    /**
     * Returns, when available, the size of the latest started transfer.
     * This is retreived by parsing the response string received as an initial
     * response to a {@code RETR} or similar request.
     *
     * @return the size of the latest transfer or -1 if either there was no
     *         transfer or the information was unavailable.
     */
    public abstract long getLastTransferSize();

    /**
     * Returns, when available, the remote name of the last transfered file.
     * This is mainly useful for "put" operation when the unique flag was
     * set since it allows to recover the unique file name created on the
     * server which may be different from the one submitted with the command.
     *
     * @return the name the latest transfered file remote name, or
     *         {@code null} if that information is unavailable.
     */
    public abstract String getLastFileName();

    /**
     * Attempts to switch to a secure, encrypted connection. This is done by
     * sending the {@code AUTH TLS} command.
     * <p>See <a href="http://www.ietf.org/rfc/rfc4217.txt">RFC 4217</a></p>
     * If successful this will establish a secure command channel with the
     * server, it will also make it so that all other transfers (e.g. a RETR
     * command) will be done over an encrypted channel as well unless a
     * {@link #reInit()} command or a {@link #endSecureSession()} command is issued.
     * <p>This method should be called after a successful {@link #connect(java.net.InetSocketAddress) }
     * but before calling {@link #login(java.lang.String, char[]) }.</p>
     *
     * @return this FtpCLient
     * @throws IOException if an error occured during the transmission.
     * @throws FtpProtocolException if the command was rejected by the server
     * @see #endSecureSession()
     */
    public abstract FtpClient startSecureSession() throws Exception;

    /**
     * 发送命令 CCC
     * @return 当前类实例
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient endSecureSession() throws Exception;

    /**
     * 此命令用于在一些主机上为新传送的文件分配足够的存储空间。
     * 参数是十进制的逻辑字 节数。如果是记录或页结构，页或记录的最大大小也需要，这在第二个参数内以十进制指定。
     * 第二个参数是可选的，如果有它，它和第一个参数以Telnet字 符<SP> R <SP>分隔。
     * 此命令在STOR或APPE命令后，对于不需要分配存储空间的机器，它的作用等于NOOP。
     * @return 当前类实例
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient allocate(long size) throws Exception;

    /**
     * 此命令使用户在不改变登录或帐户信息的情况下加载另一个文件系统数据结构。传输参数也不变。参数是文件目录或与系统相关的文件集合
     * @param struct 命令参数
     * @return       当前类实例
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient structureMount(String struct) throws Exception;

    /**
     * 返回服务器的操作系统名
     * @return 服务器的操作系统名
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract String getSystem() throws Exception;

    /**
     * 返回服务器对应的帮助信息
     * @param cmd 帮助命令参数
     * @return    对应的帮助信息
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract String getHelp(String cmd) throws Exception;

    /**
     * 发送 SITE 命令
     * @param cmd 命令参数
     * @return    当前类实例
     * @throws Exception 异常
     * 2024年3月29日
     * @author MBG
     */
    public abstract FtpClient siteCmd(String cmd) throws Exception;
}
